package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"server/src/global"
	"time"
)

func InitMysql() {
	m := global.GVL_CFG.Mysql
	mysqlCfg := mysql.Config{
		DSN:                       m.Dsn(),
		SkipInitializeWithVersion: false,
	}

	logCfg := setDBLogger()

	//连接数据库
	db, err := gorm.Open(mysql.New(mysqlCfg), logCfg)
	if err != nil {
		panic(any(fmt.Sprintln("数据库连接错误：", err)))
	}
	mysqlConnectionPool(db)
	global.GVL_DB = db
}

// 设置连接池
func mysqlConnectionPool(db *gorm.DB) {
	sqlDB, _ := db.DB()
	m := global.GVL_CFG.Mysql
	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(m.MaxIdleConns)
	// SetMaxOpenConns 设置打开数据库连接的最大数量
	sqlDB.SetMaxOpenConns(m.MaxOpenConns)
	// SetConnMaxLifetime 设置了连接可复用的最大时间
	sqlDB.SetConnMaxLifetime(time.Duration(m.MaxLifetime) * time.Minute)
}

// 设置日志
func setDBLogger() *gorm.Config {
	config := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	switch global.GVL_CFG.Mysql.LogMode {
	case "silent", "Silent":
		config.Logger = newLogger.LogMode(logger.Silent)
	case "error", "Error":
		config.Logger = newLogger.LogMode(logger.Error)
	case "warn", "Warn":
		config.Logger = newLogger.LogMode(logger.Warn)
	case "info", "Info":
		config.Logger = newLogger.LogMode(logger.Info)
	default:
		config.Logger = newLogger.LogMode(logger.Info)
	}
	return config
}
